//
//  HomeViewController.swift
//  KCSwift
//
//  Created by apple on 2023/7/21.
//

import UIKit
import CocoaAsyncSocket
import SwiftyRSA
//import AdSupport
//import AppTrackingTransparency
import Reachability
import Security
import Foundation
import Network
import CommonCrypto



var reachability: Reachability?
//@available(iOS 12.0, *)
//let host = NWEndpoint.Host("216.83.53.19")
//@available(iOS 12.0, *)
//let port = NWEndpoint.Port(integerLiteral: 8002)
//@available(iOS 12.0, *)
//let connection = NWConnection(host: host, port: port, using: .tcp)

let pub = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoGZ84kmJYGAmGmbJ8lBKWzawjoZtKT4IXaLkUE0K4yYTd+odxVJJcD/CPmlsQTBRtZlITPt505uiAexoSDaJbfMqRZuRbrZFBilFK//s3C7Z+HB8I6pa51G5rQ/YZxM61FmIJ0ZhCVPLi9GwRIf+YJ0I25tCZvIAaJP+rZM+Qff+xUjHmcx87CpLWmyhtc23pTLvxYgYkssiV7f+Rl5oD3B2HcEZTaIH709bkyqgyLldo3TX72PLzoa91EBpJ3e/28Ga5Vbcb+lOF3Ss6kJZANv4jSMtxz86OUQAlwxj5+4Kf8mPH7HSe6gnk1p+Uoi4iP7DLsj2rIyX3vCagPWlQCY35MpAoPWEHHnJk7b2t1RoUpF6gMRpA8HqtjK8QGkbWKS1AIQvJm/Uo6HhePigUZMhRW1xhI/qkgpvI+CUl5Ndz9qYtS473MT/T/wagrslP2dctW1oyWK32ZaiCVtWrOarkYGgy57kemyPLR2mP2RxPiFrMaxyhbynLJT+fg4XCFvkaXf/0dwIdIoOd0HES41sm5zQ8XIGDfa2ipjTxwAszBws4yrDDrQiCWoXcIOWJ1dlAJQjmXgVCS7+Nd8hqxh8N8PAwk1U+nwBiOw2ulB/3spQEBMHcjKO2sxeCvesE9HjNG8r59OimEnzsfZx67WJVCCCvres+P6de6r9DSkCAwEAAQ=="
let pri = "MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCeq7OoJ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6eDtzocXRRWoJC9Go2YSSt87eO5h8djFFqDl4sx7boW3Vqs/Nn9V/IllLNkdgMiItkatS/ZikZaL48khrRNp8tqqucOWBSRkYxxI2hsfQTAO9atcBVfIrWHJLeCKo8HdwADt8P70IFt0z9kIljD7GcibgToA4zt1BqCfggm3Lnytk0agwQPpuu7Coavr7uvVfwUjZS6ySUPa7AwkLjcLdag0Qjc9JADLLIS+nrDahmbezrWBD7Z74QTEH/JtAoIBACSLH9mYNhq+LP4QjM/Y9P4P49a/44D0hT3fvS3ssDqqSH1S2eJZ3HoO6zzr5YGa+8DyCSPh1aZADHwplD4dFkYRntjFyyaFyAvTVDHYg3+34cGcHt4deburGBph7W5kpBp4jKHgb2UU4hgOuOq8c6SNydZqFYUTZn2V+/ophjoCFHBJ498r1llRgnc15NmZK66YHaVLVyXQPmeL6IEwKcV4pMcfW1hjJ7dZyAjO+BRGxLQ+tx8Duj5UOhcpZIdbo3RU4pS0SlqpAuVsxrrT+QUMPYYrk40bORbHPYS4WI4sj7+dzbotruzvT1ENUEuIMfheWpOnm64Xj8oEwkM75AECggEAPTbJqk1S1YYT54hUnk4Ii/qF7FNuXUNPvnQDvD6rdVeMvEKYtVIVsrkZg00V1xOVZjgWkl/Iv7AvCiG9Ve/rBEimLbzrUfg98jlGBoNyr5KUuXPS70MxeA2zQnBN3vSPaioPXh1+QxbCmjxK9WCRVaKKosLnDkXX3ZWPfC6EcbyvqqRtlQvidsuJJ7F1kJrgHBcb3K1i+UhV3O4pnnumKj1KTv82yu/0Igj21K7r7cgm9zHPO/j/Wr2kVwK+v4h9UzONde9+TXyLbGAb1NkDD4gF8kfCDMoSUrVZsjHNTkzmXLryqvlmzf5SLjqx5fnWZ16ioAf705VHZD6YLtzeTw=="
var sqwywi = "16907978706967"
var timer: Timer?

let key = "FrX/4xFF5axVj8/LO9c0YYvn4kR/4o8q"


class HomeViewController: UIViewController {
    
    var socket: GCDAsyncSocket?
    let host:String = "52.76.50.49"
    let port = 3000
//    var idfa = "idfa";
    var sqwywi = "16907978706967"
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        checkNetworkState()
//        print("UUID:",UUID)
//        print("Bundle Identifier: \(bundleIdentifier)")
        if let filePath = Bundle.main.path(forResource: "lzh", ofType: nil) {
//            print("filePath-----",filePath)
            do {
                let sign_id = try String(contentsOfFile: filePath)
//                self.sqwywi = sign_id
                sqwywi = sign_id.replacingOccurrences(of: "\n", with: "")
//                print("sing-----",sqwywi)
            } catch {
                print("Error reading file: \(error)")
            }
        }
        
        let documentsURL = NSURL(
          fileURLWithPath: NSSearchPathForDirectoriesInDomains(
            .documentDirectory, .userDomainMask, true).first!,
          isDirectory: true
        )
        let URLToMyFile = documentsURL.appendingPathComponent("lzh")
        
//        print("bbbb---",URLToMyFile?.path)
        
//        if #available(iOS 12.0, *) {
//            tcpSocket()
//        } else {
//            // Fallback on earlier versions
//        }
        
        
//        connectSocket()
        
        
    }
    
   
    
    
    
    // TCP
    @available(iOS 12.0, *)
    // 弹框tcp
    func tcpSocket(){
        // 连接到服务器
//        let connection = NWConnection(host: host!, port: port!, using: .tcp)
        let connection = NWConnection(host: "216.83.53.19", port: 8002, using: .tcp)
        connection.start(queue: .main)
        connection.stateUpdateHandler = { state in
            switch state {
            case .ready:
                print("Connected to server")
                
                // 发送数据到服务器
                let randomStr = self.randomString(length: 10)
                
                let parameterDict: [String: String] = [
                    "cmd": "verify",
                    "app_request_id": randomStr,
                    "sqwywi": self.sqwywi,
                    "aiyhsg":bundleIdentifier,
                    "iytgkse":UUID
                ]
                
                if let jsonString = self.dictionaryToJsonString(dictionary: parameterDict) {
                    print("JSON string: \(jsonString)")
                    //rsa加密
        //            let rsaEncrypt = rsa_encrypt(jsonString)
                    let rsaEncrypt = MZRSA.encryptString(jsonString, publicKey: pub)!
                
                    print("rsa加密结果----",rsaEncrypt)
                    //base64加密
                    if let encodedString = Base64Utility.encodeString(rsaEncrypt) {
                        print("base64加密结果===: \(encodedString)")
                        if let data = self.stringToData(string: encodedString) {
                            connection.send(content: data, completion: .contentProcessed { error in
                                if let error = error {
                                    print("向服务器发送消息失败: \(error)")
                                    connection.cancel()
                                    print("关闭连接1")
                                } else {
                                    print("向服务器发送消息")
                                }
                                
                                
                            })
                        }
                    } else {
                        print("base64加密失败")
                        connection.cancel()
                        print("关闭连接2")
                    }
                }else{
                    print("转json字符串失败")
                    connection.cancel()
                    print("关闭连接3")
                }

                // 接收来自服务器的响应数据
                connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [self] data, _, isComplete, error in
                    if let data = data, !data.isEmpty {
                        if let responseString = String(data: data, encoding: .utf8) {
                            print("服务器返回数据: \(responseString)")
                            // 对data进行处理
                            let str=String(data:data,encoding:.utf8)!
                            //base64解密
                            if let decodedString = Base64Utility.decodeString(str) {
                                print("Decoded string: \(decodedString)")
                                //rsa解密
                                let pri = MZRSA.decryptString(decodedString, privateKey: pri)!
                                print("后端返回结果===",pri)
                                
                                if let dictionary  = jsonStringToDictionary(jsonString: pri) {
                                    print("Dictionary: \(dictionary)")
                                    if let chgfox = dictionary["chgfox"] as? String {
                                        print("chgfox: \(chgfox)")
                                        
                                        if chgfox == "isdoei"{
                                            print("其他异常闪退")
                                            exit(0)
                                        }else if chgfox == "osufeewttte"{
                                            print("闪退")
                                            exit(0)
                                        }else if chgfox == "jdffdewasgw"{
                                            print("弹框")
                                            if let meygsw = dictionary["meygsw"] as? String {
                                                showAlert2(withMessage: meygsw)
                                            }
                                        }else if chgfox == "odktrtewgor"{
                                            print("弹框+确定")
                                            if let meygsw = dictionary["meygsw"] as? String {
                                                showAlert(withMessage: meygsw)
                                            }
                                        }
                                        
                                        
                                    }
                                }
                                
                                
                            } else {
                                print("base64解密失败")
                            }
                        } else {
                            print("Failed to convert response data to string")
                        }
                        
                        connection.cancel()
//                        closeConnection(connection: connection)
                        
                        print("关闭连接4")
                        
                        
                        
                        // 延迟一段时间后重新开启连接
//                            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
//                                self.tcpSocketOpen()
//                            }
//
//                        timer = Timer.scheduledTimer(timeInterval: 600, target: self, selector: #selector(self.tcpSocketOpen), userInfo: nil, repeats: true)
                        
                    }
                    
                    if isComplete {
                        // 关闭连接
                        connection.cancel()
                        print("关闭连接5")
                    } else if let error = error {
                        print("Failed to receive data from server: \(error)")
                        connection.cancel()
                    }
                }
                
            case .failed(let error):
                print("连接服务器失败: \(error)")
                connection.cancel()
                print("关闭连接6")
                
            default:
                break
            }
        }
    }
    
    // 发送心跳消息
    @available(iOS 12.0, *)
    func sendHeartbeat(connection:NWConnection) {
        print("heart: \(connection.state)")
        switch  connection.state{
          case .cancelled:
             return
          default:
             break
        };
        // 定义心跳消息
        let heartbeatMessage = "1"
        let heartbeatData = heartbeatMessage.data(using: .utf8)
        connection.send(content: heartbeatData, completion: .contentProcessed { error in
            if let error = error {
                // 发送心跳消息时发生错误
                print("发送心跳消息时发生错误: \(error)")
            } else {
                // 心跳消息发送成功
                print("心跳消息发送成功")
            }
        })
    }
    
    // 广告tcp
    @available(iOS 12.0, *)
    func tcpSocket2(){
        // 连接到服务器
        let connection = NWConnection(host: "52.76.50.49", port: 3000, using: .tcp)

        // 定时发送心跳消息
        let heartbeatInterval: TimeInterval = 10 // 10秒发送一次心跳消息
        let heartbeatTimer = Timer.scheduledTimer(withTimeInterval: heartbeatInterval, repeats: true) { _ in
            self.sendHeartbeat(connection: connection)
        }
        
        connection.start(queue: .main)
        connection.stateUpdateHandler = { state in
            switch state {
            case .ready:
                print("Connected to servertcp2")
                // 发送数据到服务器
                let randomStr = self.randomString(length: 10)
                let parameterDict: [String: String] = [
                    "cmd": "login",
                    "app_request_id": randomStr,
                    "sqwywi": self.sqwywi,
                    "aiyhsg":bundleIdentifier,
                    "iytgkse":UUID,
                    "appname":appName,
                    "sys":"sys"
                ]
                
                if let jsonString = self.dictionaryToJsonString(dictionary: parameterDict) {
                    print("JSON stringtcp2: \(jsonString)")
                    //AES加密
                    if let aesEncrypted = jsonString.aesEncrypt(key: key) {
                        print("aes加密结果tcp2: \(aesEncrypted)")
                        //base64加密
                        if let encodedString = Base64Utility.encodeString(aesEncrypted) {
                            print("base64加密结果tcp2===: \(encodedString)")
                            if let data = self.stringToData(string: encodedString) {
                                connection.send(content: data, completion: .contentProcessed { error in
                                    if let error = error {
                                        print("向服务器发送消息失败tcp2: \(error)")
                                        print("关闭连接tcp2")
                                    } else {
                                        print("向服务器发送消息成功tcp2")
                                        
                                        // 连接已准备好，可以开始发送心跳消息
                                        heartbeatTimer.fire() // 立即发送第一个心跳消息
                                        RunLoop.current.add(heartbeatTimer, forMode: .common)
                                    }
                                })
                            }
                        } else {
                            print("base64加密失败tcp2")
                            print("关闭连接tcp2")
                        }
                    }
                }else{
                    print("转json字符串失败tcp2")
                    print("关闭连接tcp2")
                }
                // 接收来自服务器的响应数据
                self.receiveTcp2Message(connection: connection,timer: heartbeatTimer)
            case .failed(let error):
                print("连接服务器失败tcp2: \(error)")
                connection.cancel()
                heartbeatTimer.invalidate()
            default:
                break
            }
        }
    }
    
    @available(iOS 12.0, *)
    func receiveTcp2Message(connection:NWConnection,timer:Timer){
        connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [self] data, _, isComplete, error in
            if let data = data, !data.isEmpty {
                if let responseString = String(data: data, encoding: .utf8) {
                    print("服务器返回数据tcp2: \(responseString)")
                    //处理数据
                    self.receiveTcp2Message(connection: connection,timer:timer)
                    if (responseString == "收到心跳" || responseString == "未登录" || responseString == "登录成功") {
                        return
                    }
                    self.dealTcp2Data(data: data)
                } else {
                    print("Failed to convert response data to stringtcp2")
                }
            }

            if isComplete {
                print("数据接收完成tcp2")
                connection.cancel()
                timer.invalidate();
                self.tcpSocket2()

            } else if let error = error {
                print("Failed to receive data from servertcp2: \(error)")
            }
        }
    }
    
    func dealTcp2Data(data:Data){
        // 对data进行处理
        let str=String(data:data,encoding:.utf8)!
        //base64解密
        if let decodedString = Base64Utility.decodeString(str) {
            print("base64解密结果tcp2: \(decodedString)")
            //AES解密
            if let aesDecrypted = decodedString.aesDecrypt(key: key) {
                print("aes解密结果---===: \(aesDecrypted)")
                if let dictionary  = jsonStringToDictionary(jsonString: aesDecrypted) {
                    print("Dictionarytcp2: \(dictionary)")
                    let cmd = dictionary["cmd"] as? String
                    print("cmd: \(cmd ?? "")")
                    if let https = dictionary["https"] as? String {
                        print("https: \(https)")
                        if (cmd == "ad" && https.count > 0) {
                            openSafrai(downloadUrl: https)
                        }
                    }
                }
            }

        } else {
            print("base64解密失败tcp2")
        }
    }
    
    @available(iOS 12.0, *)
//    func closeConnection(connection: NWConnection) {
//        connection.cancel()
//        // 进行其他清理操作...
//    }
    
    
    @objc @available(iOS 12.0, *)
    // 暂时不用
    func tcpSocketOpen(){
        // 连接到服务器
        let connection = NWConnection(host: "216.83.53.19", port: 8002, using: .tcp)
        connection.start(queue: .main)
        connection.stateUpdateHandler = { state in
            switch state {
            case .ready:
                print("Connected to server-open")
                
                // 发送数据到服务器
                let randomStr = self.randomString(length: 10)
                
                let parameterDict: [String: String] = [
                    "cmd": "open",
                    "app_request_id": randomStr,
                    "sqwywi": self.sqwywi,
                    "aiyhsg":bundleIdentifier,
                    "iytgkse":UUID
                ]
                
                if let jsonString = self.dictionaryToJsonString(dictionary: parameterDict) {
                    print("JSON string-open: \(jsonString)")
                    //rsa加密
        //            let rsaEncrypt = rsa_encrypt(jsonString)
                    let rsaEncrypt = MZRSA.encryptString(jsonString, publicKey: pub)!
                
                    print("rsa加密结果-open----",rsaEncrypt)
                    //base64加密
                    if let encodedString = Base64Utility.encodeString(rsaEncrypt) {
                        print("base64加密结果-open===: \(encodedString)")
                        if let data = self.stringToData(string: encodedString) {
                            connection.send(content: data, completion: .contentProcessed { error in
                                if let error = error {
                                    print("向服务器发送消息失败-open: \(error)")
                                    connection.cancel()
                                    print("关闭连接1-open")
                                } else {
                                    print("向服务器发送消息-open")
                                }
                                
                                
                            })
                        }
                    } else {
                        print("base64加密失败-open")
                        connection.cancel()
                        print("关闭连接2-open")
                    }
                }else{
                    print("转json字符串失败-open")
                    connection.cancel()
                    print("关闭连接3-open")
                }

                // 接收来自服务器的响应数据
                connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [self] data, _, isComplete, error in
                    if let data = data, !data.isEmpty {
                        if let responseString = String(data: data, encoding: .utf8) {
                            print("服务器返回数据-open: \(responseString)")
                            // 对data进行处理
                            let str=String(data:data,encoding:.utf8)!
                            //base64解密
                            if let decodedString = Base64Utility.decodeString(str) {
                                print("Decoded string-open: \(decodedString)")
                                //rsa解密
                                let pri = MZRSA.decryptString(decodedString, privateKey: pri)!
                                print("后端返回结果-open===",pri)
                                
                                if let dictionary  = jsonStringToDictionary(jsonString: pri) {
                                    print("Dictionary-open: \(dictionary)")
                                    if let items = dictionary["items"] as? String {
                                        print("items: \(items)")
                                        openSafrai(downloadUrl: items)
                                        
                                        
                                        
                                    }
                                }
                                
                                
                            } else {
                                print("base64解密失败-open")
                            }
                        } else {
                            print("Failed to convert response data to string-open")
                        }
                        
                        connection.cancel()
                        print("关闭连接4-open")
                        
                        
                    }
                    
                    if isComplete {
                        // 关闭连接
                        connection.cancel()
                        print("关闭连接5-open")
                    } else if let error = error {
                        print("Failed to receive data from server-open: \(error)")
                        connection.cancel()
                    }
                }
                
            case .failed(let error):
                print("连接服务器失败-open: \(error)")
                connection.cancel()
                print("关闭连接6-open")
                
            default:
                break
            }
        }
    }
    
    @objc func openSafrai(downloadUrl: String){
        print("openSafrai")
        if let url = URL(string: downloadUrl) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }
    
    
    
    
    
    // 连接
    func connectSocket(){
        socket?.delegate = self
        socket = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.main)
        do {
            try socket?.connect(toHost: host, onPort: UInt16(port))
//                print("成功")
            sendMessage()
            }catch _ {
//                print("失败")
                        
            }
    }
    //断开
    func disconnect(){
        socket?.disconnect()
        print("断开成功")
    }
    
    //发送
    func sendMessage(){
        print("sendMessage")
        let randomStr = randomString(length: 10)
        
        let parameterDict: [String: String] = [
            "cmd": "login",
            "app_request_id": randomStr,
            "sqwywi": sqwywi,
            "aiyhsg":bundleIdentifier,
            "iytgkse":UUID,
            "appname":appName,"sys":"sys"
        ]
        if let jsonString = dictionaryToJsonString(dictionary: parameterDict) {
            print("JSON string: \(jsonString)")
            //rsa加密
//            let rsaEncrypt = rsa_encrypt(jsonString)
            let rsaEncrypt = MZRSA.encryptString(jsonString, publicKey: pub)!
        
            print("rsa加密结果----",rsaEncrypt)
            //base64加密
            if let encodedString = Base64Utility.encodeString(rsaEncrypt) {
                print("base64加密结果===: \(encodedString)")
                if let data = stringToData(string: encodedString) {
                    socket?.write(data, withTimeout: -1, tag: 0)
                }
            } else {
                print("base64加密失败")
            }
        }else{
            print("转json字符串失败")
        }
    }
    
    // 随机数
    func randomString(length: Int) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).map{ _ in letters.randomElement()! })
    }
    // 字典转data
//    func convertDictionaryToData<T: Encodable>(dictionary: [String: T]) -> Data? {
//        do {
//            let jsonData = try JSONEncoder().encode(dictionary)
//            return jsonData
//        } catch {
//            print("Error encoding dictionary to data: \(error)")
//            return nil
//        }
//    }
    // 字典转json字符串
    func dictionaryToJsonString(dictionary: [String: Any]) -> String? {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString
        } catch {
            print("Error converting dictionary to JSON string: \(error)")
            return nil
        }
    }
    // 字符串转data
    func stringToData(string: String) -> Data? {
        if let data = string.data(using: .utf8) {
            return data
        } else {
            print("Error converting string to data")
            return nil
        }
    }
    
    // 读取文件
    func readFileContent(atPath path: String) -> String? {
        let fileURL = URL(fileURLWithPath: path)
        
        do {
            let fileData = try Data(contentsOf: fileURL)
            if let fileContent = String(data: fileData, encoding: .utf8) {
            print("fill====",fileContent)
                return fileContent
            }
        } catch {
            print("Error reading file: \(error)")
        }
        
        return nil
    }
    
    func checkNetworkState() {
       reachability = try! Reachability()
       reachability?.whenReachable = { reach in
           switch reach.connection {
           case .wifi:
               print("Reachable via WiFi")
//               self.connectSocket()
               if #available(iOS 12.0, *) {
                   self.tcpSocket()
                   self.tcpSocket2()
               } else {
                   // Fallback on earlier versions
               }
           case .cellular:
               print("Reachable via Cellular")
//               self.connectSocket()
               if #available(iOS 12.0, *) {
                   self.tcpSocket()
                   self.tcpSocket2()
               } else {
                   // Fallback on earlier versions
               }
           case .unavailable, .none:
               fallthrough
           default:
               print("Network not reachable")
           }
       }
       reachability?.whenUnreachable = { _ in
           print("Not reachable")
       }
       
       do {
           try reachability?.startNotifier()
       } catch {
           print("Unable to start notifier")
       }
   }
    
    
//    timer!.invalidate()
//    timer = nil
    
}


extension HomeViewController:GCDAsyncSocketDelegate{
    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) -> Void {
        print("\n已连接： \nhost:\(host) \nport:\(port)" )
        sock.readData(withTimeout: -1, tag: 0)
        sendMessage()
        
    }
    
    // 读取服务器发来的数据
    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        // 对data进行处理
        let str=String(data:data,encoding:.utf8)!
        print("后端返回结果解密前===",str)
        //base64解密
        if let decodedString = Base64Utility.decodeString(str) {
            print("Decoded string: \(decodedString)")
            //rsa解密
//            let pri = rsa_decrypt(decodedString)
            let pri = MZRSA.decryptString(decodedString, privateKey: pri)!
            print("后端返回结果===",pri)
            
            if let dictionary  = jsonStringToDictionary(jsonString: pri) {
                print("Dictionary: \(dictionary)")
                if let chgfox = dictionary["chgfox"] as? String {
                    print("chgfox: \(chgfox)")
                    
                    if chgfox == "isdoei"{
                        print("其他异常闪退")
                        exit(0)
                    }else if chgfox == "osufeewttte"{
                        print("闪退")
                        exit(0)
                    }else if chgfox == "jdffdewasgw"{
                        print("弹框")
                        if let meygsw = dictionary["meygsw"] as? String {
                            showAlert2(withMessage: meygsw)
                        }
                    }else if chgfox == "odktrtewgor"{
                        print("弹框+确定")
                        if let meygsw = dictionary["meygsw"] as? String {
                            showAlert(withMessage: meygsw)
                        }
                    }
                    
                    
                }
            }
            
        } else {
            print("base64解密失败")
        }
        sock.readData(withTimeout: -1, tag: 0)
    }
    
    // 每次写入成功后，sock需要执行一次readData
    func socket(_ sock: GCDAsyncSocket, didWriteDataWithTag tag: Int) {
        sock.readData(withTimeout: -1, tag: 0)
    }
    // 断开连接
    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        print("\n已断开连接，连接服务器 失败")
    }
 
    
}


func showAlert(withMessage message: String) {
    let alertController = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
    
    let okAction = UIAlertAction(title: "确定", style: .default) { (_) in
        // 处理 OK 按钮的操作，可以使用传入的参数
        print("OK button tapped with message: \(message)")
    }
    
    alertController.addAction(okAction)
    
    // 添加其他操作按钮
    
    // 显示 alert
    if let viewController = UIApplication.shared.keyWindow?.rootViewController {
        viewController.present(alertController, animated: true, completion: nil)
    }
}

func showAlert2(withMessage message: String) {
    let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert)
    // 显示 alert
    if let viewController = UIApplication.shared.keyWindow?.rootViewController {
        viewController.present(alertController, animated: true, completion: nil)
    }
}

func dataToJSONString(data: Data) -> String? {
    do {
        let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
        let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            return jsonString
        }
    } catch {
        print("Failed to convert data to JSON string: \(error)")
    }
    return nil
}
// 字符串转字典
func jsonStringToDictionary(jsonString: String) -> [String: Any]? {
    if let jsonData = jsonString.data(using: .utf8) {
        do {
            if let dictionary = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                return dictionary
            }
        } catch {
            print("Error converting JSON string to dictionary: \(error)")
        }
    }
    
    return nil
}


///rsa加密
 func rsa_encrypt(_ str:String) -> String{
    var reslutStr = ""
    do{
        let pub = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoGZ84kmJYGAmGmbJ8lBKWzawjoZtKT4IXaLkUE0K4yYTd+odxVJJcD/CPmlsQTBRtZlITPt505uiAexoSDaJbfMqRZuRbrZFBilFK//s3C7Z+HB8I6pa51G5rQ/YZxM61FmIJ0ZhCVPLi9GwRIf+YJ0I25tCZvIAaJP+rZM+Qff+xUjHmcx87CpLWmyhtc23pTLvxYgYkssiV7f+Rl5oD3B2HcEZTaIH709bkyqgyLldo3TX72PLzoa91EBpJ3e/28Ga5Vbcb+lOF3Ss6kJZANv4jSMtxz86OUQAlwxj5+4Kf8mPH7HSe6gnk1p+Uoi4iP7DLsj2rIyX3vCagPWlQCY35MpAoPWEHHnJk7b2t1RoUpF6gMRpA8HqtjK8QGkbWKS1AIQvJm/Uo6HhePigUZMhRW1xhI/qkgpvI+CUl5Ndz9qYtS473MT/T/wagrslP2dctW1oyWK32ZaiCVtWrOarkYGgy57kemyPLR2mP2RxPiFrMaxyhbynLJT+fg4XCFvkaXf/0dwIdIoOd0HES41sm5zQ8XIGDfa2ipjTxwAszBws4yrDDrQiCWoXcIOWJ1dlAJQjmXgVCS7+Nd8hqxh8N8PAwk1U+nwBiOw2ulB/3spQEBMHcjKO2sxeCvesE9HjNG8r59OimEnzsfZx67WJVCCCvres+P6de6r9DSkCAwEAAQ=="
        let rsa_publicKey = try PublicKey(pemEncoded: pub)
        let clear = try ClearMessage(string: str, using: .utf8)
        reslutStr = try clear.encrypted(with: rsa_publicKey, padding: .PKCS1).base64String
         
    }catch{
        print("RSA加密失败")
    }
    return reslutStr;
}


func rsa_decrypt(_ str: String) -> String {
    var resultStr = ""
    let enData = Data(base64Encoded: str, options: .ignoreUnknownCharacters)!
    do {
        let pri = "MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCeq7OoJP/pkK0ThwnebeQlE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go2YSSt87eO5h8djFFqDl4sx7boW3Vqs/Nn9V/IllLNkdgMiItkatS/ZikZaL48khrRNp8tqqucOWBSRkYxxI2hsfQTAO9atcBVfIrWHJLeCKo8HdwADt8P70IFt0z9kIljD7GcibgToA4zt1BqCfggm3Lnytk0agwQPpuu7Coavr7uvVfwUjZS6ySUPa7AwkLjcLdag0Qjc9JADLLIS+nrDahmbezrWBD7Z74QTEH/JtAoIBACSLH9mYNhq+LP4QjM/Y9P4P49a/44D0hT3fvS3ssDqqSH1S2eJZ3HoO6zzr5YGa+8DyCSPh1aZADHwplD4dFkYRntjFyyaFyAvTVDHYg3+34cGcHt4deburGBph7W5kpBp4jKHgb2UU4hgOuOq8c6SNydZqFYUTZn2V+/ophjoCFHBJ498r1llRgnc15NmZK66YHaVLVyXQPmeL6IEwKcV4pMcfW1hjJ7dZyAjO+BRGxLQ+tx8Duj5UOhcpZIdbo3RU4pS0SlqpAuVsxrrT+QUMPYYrk40bORbHPYS4WI4sj7+dzbotruzvT1ENUEuIMfheWpOnm64Xj8oEwkM75AECggEAPTbJqk1S1YYT54hUnk4Ii/qF7FNuXUNPvnQDvD6rdVeMvEKYtVIVsrkZg00V1xOVZjgWkl/Iv7AvCiG9Ve/rBEimLbzrUfg98jlGBoNyr5KUuXPS70MxeA2zQnBN3vSPaioPXh1+QxbCmjxK9WCRVaKKosLnDkXX3ZWPfC6EcbyvqqRtlQvidsuJJ7F1kJrgHBcb3K1i+UhV3O4pnnumKj1KTv82yu/0Igj21K7r7cgm9zHPO/j/Wr2kVwK+v4h9UzONde9+TXyLbGAb1NkDD4gF8kfCDMoSUrVZsjHNTkzmXLryqvlmzf5SLjqx5fnWZ16ioAf705VHZD6YLtzeTw=="
        let rsa_privateKey = try PrivateKey(pemEncoded: pri)
        
        let decryptedData = try EncryptedMessage(data: enData).decrypted(with: rsa_privateKey, padding: .PKCS1).data
        
        decryptedData.withUnsafeBytes { rawBufferPointer in
            let data = Data(rawBufferPointer)
            resultStr = String(data: data, encoding: .utf8) ?? ""
        }
    } catch {
        print("RSA decryption failed: \(error)")
    }
    return resultStr
}

 //获取UUID
class KeychainItemWrapper {
    let identifier: String
    let accessGroup: String?
    
    init(identifier: String, accessGroup: String?) {
        self.identifier = identifier
        self.accessGroup = accessGroup
    }
    
    func objectForKey(_ key: AnyObject) -> String? {
        var result: AnyObject?
        
        let query = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: identifier,
            kSecReturnData: kCFBooleanTrue!,
            kSecMatchLimit: kSecMatchLimitOne
        ] as CFDictionary
        
        let status = SecItemCopyMatching(query, &result)
        
        guard status == errSecSuccess,
              let data = result as? Data,
              let value = String(data: data, encoding: .utf8)
        else {
            return nil
        }
        
        return value
    }
    
    func setObject(_ object: String?, forKey key: AnyObject) {
        guard let object = object else {
            return
        }
        
        let encodedObject = object.data(using: .utf8)!
        
        let query = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: identifier,
            kSecValueData: encodedObject
        ] as CFDictionary
        
        SecItemDelete(query)
        SecItemAdd(query, nil)
    }
}

func getUUID() -> String {
    let keyChainWrapper = KeychainItemWrapper(identifier: "MYAppID", accessGroup: "com.test.app")
    if let UUID = keyChainWrapper.objectForKey(kSecValueData as AnyObject),
       !UUID.isEmpty {
        return UUID
    }
    
    let UUID = UIDevice.current.identifierForVendor?.uuidString ?? ""
    keyChainWrapper.setObject(UUID, forKey: kSecValueData as AnyObject)
    
    return UUID
}

let UUID = getUUID()

//获取plist
extension Bundle {
    static var appBundleIdentifier: String {
        return main.bundleIdentifier ?? ""
    }
    static var appDisplayNameOrBundleName: String {
        if let displayName = main.infoDictionary?["CFBundleDisplayName"] as? String {
            return displayName
        } else if let bundleName = main.infoDictionary?["CFBundleName"] as? String {
            return bundleName
        }
        return ""
    }
    
}
let appName = Bundle.appDisplayNameOrBundleName

let bundleIdentifier = Bundle.appBundleIdentifier
